package com.seari.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.seari.bean.User;
import com.seari.pojo.MessageBean;
import com.seari.pojo.QueryDeviceList;
import com.seari.service.DeviceListService;
import com.seari.service.UserService;
import com.seari.utils.StringHelper;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;


@Controller
@RequestMapping("/")
public class LoginController {

	@Autowired
	private UserService userService;
        
        @Autowired
        private DeviceListService dls;

	/**
	 * 用户登录
	 */
	@RequestMapping(value = "dologin")
	@ResponseBody
	public MessageBean login(HttpServletRequest req) {
		String userName = req.getParameter("userName");
		String pwd = req.getParameter("password");
                String lineID = req.getParameter("lineID").trim();
                MessageBean mb = new MessageBean();
                if(StringUtils.isBlank(userName) || StringUtils.isBlank(pwd) || StringUtils.isBlank(lineID))
                {
                    mb.setType(StringHelper.MESSAGE_TYPE_ERROR);
                    mb.setMessage("用户名密码或线路ID不能为空");
                    return mb;
                }
		User user;
		user = userService.getUserByLogin(userName, pwd);
		if (null != user) {
			req.getSession().setAttribute("user", user);
			req.getSession().setAttribute("LineID", lineID);
            mb.setType(StringHelper.MESSAGE_TYPE_SUCCESS);
            mb.setMessage("登陆成功");
			return mb;
		} else {
            mb.setType(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("登陆失败");
			return mb;
		}
	}
	
	@RequestMapping(value="dologout")
	public String dologout(HttpServletRequest req){
		req.getSession().invalidate();
		//返回登陆页面，使用redirect可以绕过springmvc的prefix设置
		return "redirect:index";
	}
	
	@RequestMapping(value="main")
	public String index(HttpServletRequest req)
	{
		return "panel/index";
	}
        
    @RequestMapping(value = "getLineID")
    @ResponseBody
    public MessageBean getLineID(HttpServletRequest req)
    {
        MessageBean messageBean = new MessageBean();
        QueryDeviceList qdl = new QueryDeviceList();
        List<String> LineIDs = dls.getDeviceListLineID(qdl);
        if(!CollectionUtils.isEmpty(LineIDs) && LineIDs.size() > 0)
        {
            messageBean.setType(StringHelper.MESSAGE_TYPE_SUCCESS);
            messageBean.setData(LineIDs);
        }
        return  messageBean;
    }
}
